﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SLPropertyGrid
{
    public class PropertiesTemplateSelector : DataTemplateSelector
    {
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            Property prop = item as Property;            
            //string typeKey = null;
            DataTemplate dt = FindTemplate(prop.PropertyType, container as FrameworkElement);
            if (dt != null) return dt;
            return base.SelectTemplate(item, container);
        }

        private DataTemplate FindTemplate(Type type, FrameworkElement container)
        {
            DataTemplate template = FindTemplate("Type:"+type.Name, container);
            while ((template == null) && (type.BaseType != null))
            {
                type = type.BaseType;
                template = FindTemplate(type, container);
            }
            if (template == null)
            {
                template = FindTemplate("default", container);
            }
            return template;

        }

        private DataTemplate FindTemplate(string key, FrameworkElement container)
        {
            if (Application.Current.Resources.Contains(key))
            {
                return Application.Current.Resources[key] as DataTemplate;
            }
            if (container != null)
            {
                DataTemplate dt = container.FindResource(key) as DataTemplate;
                if (dt != null)
                    return dt;
            }
            return null;
        }
    }
}
